/**
 * Created by soul_Company on 2016/11/11 0011
 */

$(function () {
    $("#sys_court_status").find("a").attr("href", r.base_path + "system_monitor/sys_court_status?courtUid=" + r.court_id);
    $("#sys_play_info").find("a").attr("href", r.base_path + "system_monitor/sys_play_info?court=Uid" + r.court_uid);
    $("#sys_fault_condition").find("a").attr("href", r.base_path + "views/system_monitor/sys_fault_condition.html?court=" + r.court_id);
    $("#sys_meeting").find("a").attr("href", r.base_path + "views/system_monitor/sys_meeting.html?court=" + r.court_id);
    $("#sys_warning_message").find("a").attr("href", r.base_path + "system_monitor/sys_warning_message?courtUid=" + r.court_uid);
    $("#sys_equipment_management").find("a").attr("href", r.base_path + "views/system_monitor/sys_equipment_management.html?court=" + r.court_id);
    $("#sys_log_info").find("a").attr("href", r.base_path + "system_monitor/sys_log_info?courtUid=" + r.court_uid);

    _init_server_detail();
    _server_status();
    _disk_status();
    // _store();
    $('#headingOne').on('click', function () {
        if (!$('#collapseOne').hasClass('in')) {
            _init_server_detail();
            _server_status();
            _disk_status();
            _store();
        }
    });
    $('#headingTwo').on('click', function () {
        if (!$('#collapseTwo').hasClass('in')) {
            _engine();
            clearTimeout(time_detail);
            clearTimeout(time_server);
        }
    });
});
var time_detail;
var _init_server_detail = function () {
    $.get(r.base_path + 'server/updateService', {courtUid: r.court_uid, t: Math.random()}, function (result) {
        if (result && result.status == 0) {
            var data = JSON.parse(result.data);
            $("#cpu_speed").html(data.cpu_speed + "MHz");
            $("#cpu_usage").html(data.cpu_usage + "%");
            // plot.setData([getRandomData(data.cpu_usage)]);
            // plot.draw();
            $("#memory_free").html(data.memory_free + "GB");
            $("#memory_usage").html(data.memory_usage + "GB");
            var memory = [], memory_free = {}, memory_use = {};
            memory_free.name = '空余内存';
            memory_free.value = data.memory_free;
            memory.push(memory_free);
            memory_use.name = '可用内存';
            memory_use.value = data.memory_usage;
            memory.push(memory_use);
            // _init_memory_chart(memory);
            $("#network_recevie").html(data.network_recevie + "Kbps");
            $("#network_send").html(data.network_send + "Kbps");
            time_detail = setTimeout(_init_server_detail, 30000);
        } else {
            $("#stroge_panel").html('<span class="cmp-err-msg-white">存储设备连接失败,请重试!</span>');
            clearTimeout(time_detail);
        }
        $("#loading").hide();
    }).fail(function () {
        $("#loading").hide();
        $("#stroge_panel").html('<span class="cmp-err-msg-white">服务器连接失败,请重试!</span>');
        clearTimeout(time_detail);
    });

};

var data = [],
    totalPoints = 20;

var time_server;
var _server_status = function () {
    $.get(r.base_path + 'server/showServerStatus', {courtUid: r.court_uid}, function (result) {
        if (result && result.status == 0) {
            var data = JSON.parse(result.data);
            var time_arr = new Date();
            var arr = [time_arr, time_arr - 600000, time_arr - 1200000, time_arr - 1800000, time_arr - 2400000, time_arr - 3000000, time_arr - 3600000, time_arr - 4200000, time_arr - 4800000, time_arr - 5400000];
            arr.sort(function (a, b) {
                return a - b;
            });
            eval('cpu_list=' + data.cpu_list);
            _initCpuChart(arr);

            eval('memory_list=' + data.memory_list);
            _initMemoryChart(arr);

            eval('network_list=' + data.network_list);
            _initNetworkChart(arr);
            time_server = setTimeout(_server_status, 30000);
            $("#loading").hide();
        } else {
            $("#stroge_panel").html('<span class="cmp-err-msg-white">存储设备连接失败,请重试!</span>');
            clearTimeout(time_server);
            $("#loading").hide();
        }
    }, 'json').fail(function () {
        $("#loading").hide();
        $("#stroge_panel").html('<span class="cmp-err-msg-white">服务器连接失败,请重试!</span>');
        clearTimeout(time_server);
    });

};
var _disk_status = function () {
    $.get(r.base_path + 'server/diskStatus', {courtUid: r.court_uid}, function (result) {
        if (result && result.status == 0) {
            var data = JSON.parse(result.data);
            // console.info(result);
            board_space(data.board);
            chart_disk(data.disk_size, Math.floor(data.disk_usage * 100) / 100);
            $("#loading").hide();
        } else {
            $("#stroge_panel").html('<span class="cmp-err-msg-white">存储设备连接失败,请重试!</span>');
            $("#loading").hide();
        }
    }).fail(function () {
        $("#loading").hide();
        $("#stroge_panel").html('<span class="cmp-err-msg-white">服务器连接失败,请重试!</span>');
    });
};

var court_panel_clone = $('#court_panel_clone').clone();
var _store = function () {
    $('#court_panel').empty();
    $.get(r.base_path + 'server/store', {courtId: r.court_uid}, function (result) {
        if (result && result.status == 0) {
            $(result.data).each(function (i, n) {
                var temp = court_panel_clone.clone();
                temp.find('.text-left').find('span').html(n.courtname);
                temp.find('.court-device').addClass(n.court_id);
                $(n.cfg).each(function (index, m) {
                    if (m.isrecord == 1) {
                        temp.find('.court-device').append('<div class="status-device" title="设备正常工作"><span class="status-badge status-badge-success"></span>' + m.chnname + '</div>')
                    } else {
                        temp.find('.court-device').append('<div class="status-device" title="设备未开启录像"><span class="status-badge status-badge-default"></span>' + m.chnname + '</div>')
                    }
                });
                $('#court_panel').append(temp);
            });
            $('.status-device').click(function () {
                // console.log('ok',this.parent);
            });
            $("#loading").hide();
        } else {
            $("#court_panel").html('<span class="cmp-err-msg-white">暂时没有正在录制的法庭.</span>');
            $("#loading").hide();
        }
    }).fail(function () {
        $("#loading").hide();
        $("#court_panel").html('<span class="cmp-err-msg-white">服务器连接失败,请重试!</span>');
    });
    $('#court_panel').show();
};

var cpu_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var memory_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var network_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

function _initCpuChart(arr) {
    var grid = {
        x: "10%",
        y: "10%",
        x2: "5%",
        y2: "25%"
    };
    var cpu_chart = echarts.init(document.getElementById('chart_cpu'));
    var cpu_chart_option = {
        grid: grid,
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: format_date(arr),
                splitLine: {
                    lineStyle: {
                        color: '#1a4d8e'
                    }
                },
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#fff'
                    }
                },
                axisLine: {
                    show: false
                },
                axisTick: {
                    length: 0
                }
            }
        ],
        yAxis: {
            type: 'value',
            max: 50,
            axisLine: {
                show: true,
                onZero: true,
                lineStyle: {
                    color: "#1a4d8e"
                }
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#1a4d8e'
                }
            }
        },
        series: [
            {
                type: 'line',
                itemStyle: {
                    normal: {
                        areaStyle: {
                            color: 'rgba(41,160,164,0.5)'
                        },
                        lineStyle: {
                            color: '#299796'
                        }
                    }
                },
                symbol: 'none',
                data: cpu_list
            }
        ]
    };
    //CPU使用率
    cpu_chart.setOption(cpu_chart_option);
    window.onresize = cpu_chart.resize;
}

function format_date(val) {
    var arr = [];
    $(val).each(function (i, n) {
        var data = new Date(n);
        var minute = data.getMinutes();
        arr.push(data.getHours() + ':' + (minute < 9 ? '0' + minute : minute));
    });
    return arr;
}
function _initMemoryChart(arr) {
    var grid = {
        x: "10%",
        y: "10%",
        x2: "5%",
        y2: "25%"
    };
    //内存
    var memory_chart = echarts.init(document.getElementById('chart_memory'));
    var memory_chart_option = {
        grid: grid,
        xAxis: {
            type: 'category',
            data: format_date(arr),
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#374493',
                    width: 1
                }
            },
            axisLabel: {
                show: true,
                textStyle: {
                    color: '#fff'
                }
            },
            axisLine: {
                show: false
            },
            axisTick: {
                length: 0
            },
            boundaryGap: false
        }
        ,
        yAxis: {
            axisLine: {
                show: false,
                onZero: true,
                lineStyle: {
                    color: "#1a4d8e"
                }
            },
            type: 'value',
            max: 100,
            axisLabel: {
                show: false
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#374493'
                }
            }
        },
        series: [
            {
                name: '成交',
                type: 'line',
                itemStyle: {
                    normal: {
                        areaStyle: {
                            color: 'rgba(161,106,223,0.5)'
                        },
                        lineStyle: {
                            color: '#374493'
                        }
                    }
                },
                symbol: 'none',
                data: memory_list
            }
        ]
    };
    memory_chart.setOption(memory_chart_option);
    window.onresize = memory_chart.resize;
}
function _initNetworkChart(arr) {
    var grid = {
        x: "10%",
        y: "10%",
        x2: "5%",
        y2: "25%"
    };
    //网络
    var network_chart = echarts.init(document.getElementById('chart_network'));
    var network_chart_option = {
        grid: grid,
        xAxis: {
            type: 'category',
            data: format_date(arr),
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#274b7b',
                    width: 1
                }
            },
            axisLabel: {
                show: true,
                textStyle: {
                    color: '#fff'
                }
            },
            axisLine: {
                show: false
            },
            axisTick: {
                length: 0
            },
            boundaryGap: false
        },
        yAxis: {
            axisLine: {
                show: false,
                onZero: true,
                lineStyle: {
                    color: "#1a4d8e"
                }
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#274b7b'
                }
            }
        },
        series: [
            {
                type: 'line',
                itemStyle: {
                    normal: {
                        areaStyle: {
                            color: 'rgba(224,151,108,0.5)'
                        },
                        lineStyle: {
                            color: '#df986a'
                        }
                    }
                },
                symbol: 'none',
                data: network_list
            }
        ]
    };
    network_chart.setOption(network_chart_option);
    window.onresize = network_chart.resize;
}
function board_space(board) {
    var myChart = echarts.init(document.getElementById('chart_board'));
    var option = {
        series: [
            {
                name: 'CPU温度',
                type: 'gauge',
                splitNumber: 4,       // 分割段数，默认为5
                axisLine: {            // 坐标轴线
                    lineStyle: {       // 属性lineStyle控制线条样式
                        color: [[0.2, '#228b22'], [0.8, '#48b'], [1, '#ff4500']],
                        width: 4
                    }
                },
                axisTick: {            // 坐标轴小标记
                    splitNumber: 10,   // 每份split细分多少段
                    length: 12,        // 属性length控制线长
                    lineStyle: {       // 属性lineStyle控制线条样式
                        color: 'auto'
                    }
                },
                splitLine: {           // 分隔线
                    show: true,        // 默认显示，属性show控制显示与否
                    length: 12,         // 属性length控制线长
                    lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                        color: 'auto'
                    }
                },
                pointer: {
                    width: 2
                },
                data: [{value: board}],
                detail: {
                    textStyle: {
                        fontSize: 16
                    },
                    formatter: '{value}℃'
                }
            }
        ]
    };
    myChart.setOption(option);

}
function chart_disk(disksize, diskusage) {
    //磁盘空间
    var myChart = echarts.init(document.getElementById('chart_disk'), "shine");
    var label1 = {
        normal: {
            color: '#cdb725',
            label: {
                show: true,
                position: 'center',
                formatter: '{b}{c}GB',
                textStyle: {
                    baseline: 'top',
                    fontSize: 10
                }
            },
            labelLine: {
                show: false
            }
        }
    };
    var label2 = {
        normal: {
            color: '#0c336a',
            label: {
                show: true,
                position: 'center',
                formatter: "{b}{c}GB",
                textStyle: {
                    baseline: 'bottom',
                    fontSize: 10,
                    color: "#FF4500"
                }
            },
            labelLine: {
                show: false
            }
        }
    };
    var radius = [35, 50];
    var option = {
        title: {
            text: '总容量' + disksize + 'GB',
            x: 'center',
            y: '8',
            textStyle: {
                fontSize: 12,
                color: '#FFFFFF'
            }
        },
        series: [
            {
                type: 'pie',
                radius: radius,
                x: '0%', // for funnel
                data: [
                    {name: '已用', value: diskusage, itemStyle: label1},
                    {name: '剩余', value: (disksize - diskusage).toFixed(2), itemStyle: label2}
                ]
            }
        ]
    };
    myChart.setOption(option);
}

//主机设备
var panel = $('#clone_panel').clone();
$('#clone_panel').remove();
var _engine = function () {
    $("#loading").show();
    $('#engine_panel').empty();
    $.get(r.base_path + 'device/getDevStatus', {courtId: r.court_id}, function (result) {
        if (result && result.status == 0) {
            if (!result.data) {
                $("#engine_panel").html('<span class="cmp-err-msg-white">没有找到庭审主机!</span>');
                $("#loading").hide();
                return;
            }
            var data = JSON.parse(result.data);
            console.info(data);
            data.sort(function (a, b) {
                return a.courtroomname - b.courtroomname;
            });
            $(data).each(function (i, n) {
                var temp = panel.clone();
                var label1 = {
                    normal: {
                        color: '#2306cd',
                        label: {
                            show: true,
                            position: 'center',
                            formatter: "{b}{c}GB",
                            textStyle: {
                                baseline: 'bottom',
                                fontSize: 10,
                                color: "#ddd"
                            }
                        },
                        labelLine: {
                            show: false
                        }
                    }
                };
                var label2 = {
                    normal: {
                        color: '#08cba3',
                        label: {
                            show: true,
                            position: 'center',
                            formatter: "{b}{c}GB",
                            textStyle: {
                                baseline: 'bottom',
                                fontSize: 10,
                                color: "#ddd"
                            }
                        },
                        labelLine: {
                            show: false
                        }
                    }
                };
                if (n.cpu) {
                    temp.find('h5').html(n.courtroomname);
                    temp.find('.cpu0').html('主cpu:' + n.cpu);
                    temp.find('.cpu0').addClass('fa-paper-plane-o');
                    temp.find('.cpu1').html('cpu-1:' + n.cpu1);
                    temp.find('.cpu1').addClass('fa-paper-plane-o');
                    temp.find('.mem').html('主内存:' + n.mem);
                    temp.find('.mem').addClass('fa-server');
                    temp.find('.mem1').html('内存-1:' + n.mem1);
                    temp.find('.mem1').addClass('fa-server');
                    temp.find('.fa-hdd-o').after('' + n.totalsize);
                    temp.find('.disk-pie').attr('id', n.uid);
                    n.freedisk = n.freedisk.split('G')[0];
                    n.totalsize = n.totalsize.split('G')[0];
                    $('#engine_panel').append(temp);
                    var myChart = echarts.init(document.getElementById(n.uid));
                    var radius = [35, 50];
                    var option = {
                        series: [
                            {
                                type: 'pie',
                                radius: radius,
                                x: '20%', // for funnel
                                data: [
                                    {name: '已用', value: (n.totalsize - n.freedisk), itemStyle: label1},
                                    {name: '剩余', value: n.freedisk, itemStyle: label2}
                                ]
                            }
                        ]
                    };
                    myChart.setOption(option);
                } else {
                    temp.find('h5').html(n.courtroomname);
                    temp.find('.panel-footer').html('离线');
                    $('#engine_panel').append(temp);
                }
            });
            $("#loading").hide();
        } else {
            $("#engine_panel").html('<span class="cmp-err-msg-white">庭审主机设备连接失败,请重试!</span>');
            $("#loading").hide();
        }
    }).fail(function () {
        $("#loading").hide();
        $("#engine_panel").html('<span class="cmp-err-msg-white">服务器连接失败,请重试!</span>');
    });
};
